<template>
  <div class="dept-management-container">
    <!-- 搜索区域 -->
    <ContentWrap class="search-wrapper">
      <div class="search-header">
        <div class="header-icon">
          <Icon icon="ep:search" />
        </div>
        <div class="header-content">
          <h4 class="search-title">部门管理</h4>
          <p class="search-subtitle">查询和管理组织部门结构</p>
        </div>
      </div>

      <div class="search-form-container">
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="100px"
          label-position="left"
          class="enhanced-search-form"
        >
          <div class="form-row">
            <el-form-item label="部门名称" prop="title" class="form-item">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入部门名称"
                clearable
                class="enhanced-input"
              >
                <template #prefix>
                  <Icon icon="ep:office-building" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="部门状态" prop="status" class="form-item">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择部门状态"
                clearable
                class="enhanced-select"
              >
                <template #prefix>
                  <Icon icon="ep:switch" />
                </template>
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                  <div class="option-item">
                    <Icon
                      :icon="dict.value === 0 ? 'ep:check' : 'ep:close'"
                      class="option-icon"
                      :class="dict.value === 0 ? 'success' : 'danger'"
                    />
                    <span>{{ dict.label }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>

        <div class="form-actions">
          <div class="action-group search-group">
            <el-button @click="handleQuery" type="primary" class="action-btn search-btn">
              <Icon icon="ep:search" class="btn-icon" />
              搜索
            </el-button>
            <el-button @click="resetQuery" class="action-btn reset-btn">
              <Icon icon="ep:refresh" class="btn-icon" />
              重置
            </el-button>
          </div>

          <div class="action-group operation-group">
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['system:dept:create']"
              class="action-btn add-btn"
            >
              <Icon icon="ep:plus" class="btn-icon" />
              新增
            </el-button>
            <el-button type="warning" plain @click="toggleExpandAll" class="action-btn expand-btn">
              <Icon icon="ep:sort" class="btn-icon" />
              展开/折叠
            </el-button>
          </div>
        </div>
      </div>
    </ContentWrap>

    <!-- 列表区域 -->
    <ContentWrap class="table-wrapper">
      <div class="table-header">
        <div class="header-icon">
          <Icon icon="ep:list" />
        </div>
        <div class="header-content">
          <h4 class="table-title">部门列表</h4>
          <p class="table-subtitle">组织架构树形展示</p>
        </div>
      </div>

      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="list"
          row-key="id"
          :default-expand-all="isExpandAll"
          v-if="refreshTable"
          class="enhanced-table"
          :header-cell-style="{ background: '#f8f9ff', color: '#303133', fontWeight: '600' }"
        >
          <el-table-column prop="name" label="部门名称">
            <template #default="scope">
              <div class="name-cell">
                <Icon icon="ep:office-building" class="cell-icon" />
                <span class="cell-text">{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="leader" label="负责人">
            <template #default="scope">
              <div class="leader-cell">
                <Icon icon="ep:user" class="cell-icon" />
                <span class="cell-text">
                  {{ userList.find((user) => user.id === scope.row.leaderUserId)?.nickname || '-' }}
                </span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="sort" label="排序">
            <template #default="scope">
              <div class="sort-cell">
                <Icon icon="ep:sort" class="cell-icon" />
                <span class="sort-number">{{ scope.row.sort }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <div class="status-cell">
                <dict-tag
                  :type="DICT_TYPE.COMMON_STATUS"
                  :value="scope.row.status"
                  class="enhanced-tag"
                />
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="220"
            :formatter="dateFormatter"
          >
            <template #default="scope">
              <div class="time-cell">
                <Icon icon="ep:clock" class="cell-icon" />
                <span class="cell-text">{{
                  dateFormatter(scope.row, null, scope.row.createTime)
                }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template #default="scope">
              <div class="action-cell">
                <el-button
                  link
                  type="primary"
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['system:dept:update']"
                  class="action-button edit-btn"
                >
                  <Icon icon="ep:edit" class="btn-icon" />
                  修改
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['system:dept:delete']"
                  class="action-button delete-btn"
                >
                  <Icon icon="ep:delete" class="btn-icon" />
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </ContentWrap>

    <!-- 表单弹窗：添加/修改 -->
    <DeptForm ref="formRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import DeptForm from './DeptForm.vue'
import * as UserApi from '@/api/system/user'

defineOptions({ name: 'SystemDept' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  name: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeptApi.getDeptPage(queryParams)
    list.value = handleTree(data)
  } finally {
    loading.value = false
  }
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeptApi.deleteDept(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 获取用户列表
  userList.value = await UserApi.getSimpleUserList()
})
</script>

<style lang="scss" scoped>
// 主题色变量
$primary-color: #0052cc;
$primary-light: rgba(0, 82, 204, 0.1);
$primary-border: rgba(0, 82, 204, 0.3);
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$info-color: #909399;
$text-primary: #303133;
$text-regular: #606266;
$text-secondary: #909399;
$text-placeholder: #c0c4cc;
$border-color: #dcdfe6;
$border-light: #e4e7ed;
$bg-color: #f5f7fa;
$shadow-light: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
$shadow-base:
  0 2px 4px rgba(0, 0, 0, 0.12),
  0 0 6px rgba(0, 0, 0, 0.04);
$border-radius: 12px;
$border-radius-small: 8px;

.dept-management-container {
  padding: 0;
  background: $bg-color;
  min-height: 100vh;

  @media (max-width: 768px) {
    padding: 0;
  }
}

/* 搜索区域样式 */
.search-wrapper {
  margin-bottom: 16px;
  border-radius: $border-radius;
  overflow: hidden;
  box-shadow: $shadow-light;
  border: 1px solid $border-light;

  :deep(.el-card__body) {
    padding: 0;
  }
}

.search-header {
  display: flex;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, $primary-color 0%, #1d4ed8 100%);
  color: white;

  @media (max-width: 768px) {
    padding: 16px 20px;
    flex-direction: column;
    gap: 8px;
    text-align: center;
  }
}
:deep(.cell) {
  display: flex;
  align-items: center;
}
.header-icon {
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: $border-radius-small;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;

  @media (max-width: 768px) {
    width: 36px;
    height: 36px;
    font-size: 16px;
  }
}

.header-content {
  flex: 1;
  margin-left: 12px;

  @media (max-width: 768px) {
    margin-left: 0;
  }
}

.search-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;

  @media (max-width: 768px) {
    font-size: 16px;
  }
}

.search-subtitle {
  font-size: 13px;
  opacity: 0.9;
  margin: 0;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

.search-form-container {
  padding: 24px;
  background: white;

  @media (max-width: 768px) {
    padding: 16px;
  }
}

.enhanced-search-form {
  .form-row {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 20px;

    @media (max-width: 768px) {
      flex-direction: column;
      gap: 12px;
      margin-bottom: 16px;
    }
  }

  .form-item {
    flex: 1;
    min-width: 260px;
    margin-bottom: 0;

    @media (max-width: 768px) {
      min-width: auto;
      flex: none;
    }

    :deep(.el-form-item__label) {
      font-weight: 600;
      color: $text-regular;
      padding-bottom: 8px;

      @media (max-width: 768px) {
        font-size: 14px;
        width: 100% !important;
        text-align: left !important;
        margin-bottom: 8px;
      }
    }

    :deep(.el-form-item__content) {
      @media (max-width: 768px) {
        margin-left: 0 !important;
      }
    }
  }

  // H5适配：表单项垂直布局
  @media (max-width: 768px) {
    :deep(.el-form-item) {
      display: block;
    }
  }
}

/* 输入框样式 */
.enhanced-input {
  width: 100%;

  :deep(.el-input__wrapper) {
    border-radius: $border-radius-small;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;
    padding: 12px 16px;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
      border-color: $primary-color;
    }
  }
}

/* 选择器样式 */
.enhanced-select {
  width: 100%;

  :deep(.el-select__wrapper) {
    border-radius: $border-radius-small;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;
    padding: 8px 16px;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focused {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
      border-color: $primary-color;
    }
  }
}

/* 选项样式 */
.option-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.option-icon {
  font-size: 14px;

  &.success {
    color: $success-color;
  }

  &.danger {
    color: $danger-color;
  }
}

/* 操作按钮区域 */
.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;

  @media (max-width: 768px) {
    flex-direction: column;
    gap: 12px;
  }
}

.action-group {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;

  @media (max-width: 768px) {
    width: 100%;
    justify-content: center;
  }

  &.search-group {
    @media (max-width: 768px) {
      order: 1;
    }
  }

  &.operation-group {
    @media (max-width: 768px) {
      order: 2;
      flex-direction: column;
    }
  }
}

.action-btn {
  border-radius: $border-radius-small;
  padding: 10px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;

  &:hover {
    transform: translateY(-1px);
  }

  @media (max-width: 768px) {
    width: 100%;
    justify-content: center;
    padding: 12px 16px;
  }

  .btn-icon {
    font-size: 14px;
  }

  &.search-btn {
    background: linear-gradient(135deg, $primary-color 0%, #1d4ed8 100%);
    border: none;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
    }
  }

  &.reset-btn {
    border: 2px solid $border-color;
    color: $text-regular;

    &:hover {
      border-color: $primary-color;
      color: $primary-color;
      background: $primary-light;
    }
  }

  &.add-btn {
    border: 2px solid $primary-color;
    color: $primary-color;

    &:hover {
      background: $primary-color;
      color: white;
    }
  }

  &.expand-btn {
    border: 2px solid $warning-color;
    color: $warning-color;

    &:hover {
      background: $warning-color;
      color: white;
    }
  }
}

/* 表格区域样式 */
.table-wrapper {
  border-radius: $border-radius;
  overflow: hidden;
  box-shadow: $shadow-light;
  border: 1px solid $border-light;

  :deep(.el-card__body) {
    padding: 0;
  }
}

.table-header {
  display: flex;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, $primary-color 0%, #1d4ed8 100%);
  color: white;

  @media (max-width: 768px) {
    padding: 16px 20px;
    flex-direction: column;
    gap: 8px;
    text-align: center;
  }
}

.table-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;

  @media (max-width: 768px) {
    font-size: 16px;
  }
}

.table-subtitle {
  font-size: 13px;
  opacity: 0.9;
  margin: 0;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

.table-container {
  background: white;
  overflow-x: auto;
}

.enhanced-table {
  :deep(.el-table__header) {
    th {
      background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%) !important;
      color: $text-primary !important;
      font-weight: 600 !important;
      border-bottom: 2px solid $primary-light;
      padding: 16px 12px;
    }
  }

  :deep(.el-table__body) {
    tr {
      transition: all 0.3s ease;

      &:hover {
        background: $primary-light !important;
      }

      td {
        padding: 14px 12px;
        border-bottom: 1px solid $border-light;
      }
    }

    .el-table__row--striped {
      background: #fafbff;

      &:hover {
        background: $primary-light !important;
      }
    }
  }

  // 树形表格展开图标样式
  :deep(.el-table__expand-icon) {
    color: $primary-color;
    font-size: 14px;
    transition: all 0.3s ease;

    &:hover {
      color: #1d4ed8;
      transform: scale(1.1);
    }
  }

  // H5适配
  @media (max-width: 768px) {
    :deep(.el-table__header) th {
      padding: 12px 8px;
      font-size: 13px;
    }

    :deep(.el-table__body) td {
      padding: 12px 8px;
      font-size: 12px;
    }
  }
}
/* 表格单元格样式 */
.name-cell,
.leader-cell,
.time-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: flex-start;
}

.sort-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.status-cell {
  display: flex;
  justify-content: center;
}

.cell-icon {
  font-size: 14px;
  flex-shrink: 0;
  color: $primary-color;
}

.cell-text {
  color: $text-regular;
  font-weight: 500;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

.sort-number {
  background: $primary-light;
  color: $primary-color;
  padding: 2px 8px;
  border-radius: 6px;
  font-weight: 600;
  font-size: 12px;
  min-width: 24px;
  text-align: center;

  @media (max-width: 768px) {
    font-size: 11px;
    padding: 1px 6px;
  }
}

/* 标签样式 */
.enhanced-tag {
  :deep(.el-tag) {
    border-radius: 6px;
    font-weight: 500;
    padding: 4px 8px;
    font-size: 12px;

    @media (max-width: 768px) {
      font-size: 11px;
      padding: 3px 6px;
    }
  }
}

/* 操作按钮 */
.action-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;

  @media (max-width: 768px) {
    flex-direction: column;
    gap: 4px;
  }
}

.action-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.05);
  }

  .btn-icon {
    font-size: 12px;
  }

  @media (max-width: 768px) {
    padding: 4px 8px;
    font-size: 11px;
    width: 100%;
    justify-content: center;
  }

  &.edit-btn:hover {
    background: rgba(0, 82, 204, 0.1);
    color: $primary-color;
  }

  &.delete-btn:hover {
    background: rgba(245, 108, 108, 0.1);
    color: $danger-color;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .dept-management-container {
    background: #1f2937;
  }

  .search-wrapper,
  .table-wrapper {
    background: #374151;
    border-color: #4b5563;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  }

  .search-form-container,
  .table-container {
    background: #374151;
  }

  .search-title,
  .table-title {
    color: #f9fafb;
  }

  .cell-text {
    color: #f9fafb;
  }

  .sort-number {
    background: rgba(96, 165, 250, 0.1);
    color: #60a5fa;
  }

  .enhanced-table {
    :deep(.el-table__header) {
      th {
        background: #4b5563 !important;
        color: #f9fafb !important;
        border-bottom-color: #6b7280;
      }
    }

    :deep(.el-table__cell) {
      border-bottom-color: #4b5563;
    }

    :deep(.el-table__expand-icon) {
      color: #60a5fa;

      &:hover {
        color: #93c5fd;
      }
    }
  }

  .enhanced-input,
  .enhanced-select {
    :deep(.el-input__wrapper),
    :deep(.el-select__wrapper) {
      background: #4b5563;
      border-color: #6b7280;

      .el-input__inner {
        color: #f9fafb;
      }
    }
  }

  .option-icon {
    &.success {
      color: #34d399;
    }

    &.danger {
      color: #f87171;
    }
  }
}

/* 响应式优化 */
@media (max-width: 480px) {
  .search-header,
  .table-header {
    padding: 12px 16px;
  }

  .search-form-container {
    padding: 12px;
  }

  .enhanced-table {
    :deep(.el-table__header) th {
      padding: 10px 6px;
      font-size: 12px;
    }

    :deep(.el-table__body) td {
      padding: 10px 6px;
      font-size: 11px;
    }
  }

  .cell-text {
    font-size: 11px;
  }

  .action-button {
    padding: 3px 6px;
    font-size: 10px;
  }

  .sort-number {
    font-size: 10px;
    padding: 1px 4px;
  }

  .enhanced-tag {
    :deep(.el-tag) {
      font-size: 10px;
      padding: 2px 4px;
    }
  }
}
</style>
